<template>
	<el-dialog title="修改姓名" :visible.sync="show" :before-close="cancel">
		<el-form :model="modifyAgentRealNameData" :rules="formRules" label-width="100px" ref="formRef" @submit.native.prevent>
			<el-form-item label="姓名" prop="fullName">
				<el-input v-model="modifyAgentRealNameData.fullName" placeholder="请输入新的姓名" minlength="2" maxlength="16"></el-input>
			</el-form-item>
		</el-form>
		<div class="btns">
			<el-button @click="cancel">取消</el-button>
			<el-button type="primary" @click="submit">确认</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import { modifyUserFullName } from '@/api/api';
import FormReg from '@/utils/regexp';

export default {
	components: {},
	props: {
		show: {
			type: Boolean,
			default: false
		},
		account: {
			type: Object,
			default: () => {}
		}
	},
	data() {
		var validateAgentName = (rule, value, callback) => {
			if (value.replace(FormReg.reg9, '').length !== 0) {
				callback(new Error('姓名格式错误，姓名只能是英文或中文！'));
			} else if (value.trim() === '') {
				callback(new Error('姓名为空！'));
			} else if (value.trim().length > 16 || value.trim().length < 2) {
				callback(new Error('姓名格式错误，姓名长度为2-16位！'));
			} else {
				callback();
			}
		};
		return {
			modifyAgentRealNameData: {
				fullName: '',
			},
			formRules: {
				fullName: [
					{ required: true, message: '姓名不能为空', trigger: ['blur', 'change'] },
					{ validator: validateAgentName, trigger: 'blur' }
				]
			}
		};
	},
	watch: {
		show(newVal) {
			if (newVal) {
				this.$nextTick(() => {
					this.$refs['formRef'].clearValidate();
				});
			}
		}
	},
	computed: {
		...mapState({
			loginInfo: state => state.login.userInfo
		})
	},
	mounted() {},
	methods: {
		submit() {
			this.$refs.formRef.validate(valid => {
				if (valid){
					modifyUserFullName(this.account.userId, this.modifyAgentRealNameData.fullName).then(res => {
						this.$emit('modifyUserFullNameSuccess', this.modifyAgentRealNameData.fullName);
						this.$refs['formRef'].resetFields();
					}).catch (error => {
						switch (error.code + "") {
							case '1001' : 
								this.$message.error('用户不存在！');
								break;
							default:
								this.$message.error(error);
								break;
						}
					});
				}
			});
		},
		cancel() {
			this.$refs['formRef'].resetFields();
			this.$emit('close');
		},
	}
};
</script>

<style lang="less">
.account {
	.btns {
		text-align: right;
	}
	.head {
		padding: 20px 0;
	}
	.el-avatar > img {
		width: 100%;
	}
}
</style>
